package org.tity.commons.lang;

/**
 * @author fangjieli 
 * */
public class BytesUtil {

	private static final int EIGHT=8;
	private static final int FOUR=8;
	
	/**
	 * long 转 byte[]
	 * @param values long值
	 * @return byte[]值
	 * */
	public static byte[] long2bytes(long values) {
		byte[] buffer = new byte[8];
		for (int i = 0; i < EIGHT; i++) {
			int offset = 64 - (i + 1) * 8;
			buffer[i] = (byte) ((values >> offset) & 0xff);
		}
		return buffer;
	}

	/**
	 * byte[] 转 long
	 * @param buffer byte[]值
	 * @return long值
	 * */
	public static long bytes2long(byte[] buffer) {
		long values = 0;
		for (int i = 0; i < EIGHT; i++) {
			values <<= 8;
			values |= (buffer[i] & 0xff);
		}
		return values;
	}

	/**
	 * double 转 byte[]
	 * @param d double值
	 * @return byte[]值
	 * */
	public static byte[] double2bytes(double d) {
		long value = Double.doubleToRawLongBits(d);
		byte[] byteRet = new byte[8];
		for (int i = 0; i < EIGHT; i++) {
			byteRet[i] = (byte) ((value >> 8 * i) & 0xff);
		}
		return byteRet;
	}

	/**
	 * byte[] 转 double
	 * @param arr byte[]值
	 * @return byte[]值
	 * */
	public static double bytes2double(byte[] arr) {
		long value = 0;
		for (int i = 0; i < EIGHT; i++) {
			value |= ((long) (arr[i] & 0xff)) << (8 * i);
		}
		return Double.longBitsToDouble(value);
	}

	/**
	 * int 转 byte[]
	 * @param num int值
	 * @return byte[]值
	 * */
	public static byte[] int2bytes(int num) {
		byte[] result = new byte[4];
		result[0] = (byte) ((num >>> 24) & 0xff);
		result[1] = (byte) ((num >>> 16) & 0xff);
		result[2] = (byte) ((num >>> 8) & 0xff);
		result[3] = (byte) ((num >>> 0) & 0xff);
		return result;
	}

	/**
	 * 高位在前，低位在后
	 * @param bytes byte[]
	 * @return int值
	 */
	public static int bytes2int(byte[] bytes) {
		int result = 0;
		if (bytes.length == FOUR) {
			int a = (bytes[0] & 0xff) << 24;
			int b = (bytes[1] & 0xff) << 16;
			int c = (bytes[2] & 0xff) << 8;
			int d = (bytes[3] & 0xff);
			result = a | b | c | d;
		}
		return result;
	}

}
